package com.fenghongzhang.welcometest;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;


/**
 * A simple {@link Fragment} subclass.
 */
public class TwoFragment extends Fragment {
    private TextView fgText;
    private Button btn;

    private int time = 5;
    private Timer timer;
    //等页面来通知我,开始倒计时
    public Handler handler  = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == 110){
                //子线程
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(120);
                    }
                },0,1000);

            }else if(msg.what == 120){
                time--;
                fgText.setText("倒计时"+time+"秒"); //倒计时: +秒
                //0的时候跳转.并且停止计时
                if(time == 0){
                    timer.cancel();
                    //跳转
                    Intent intent = new Intent(getActivity(), Main2Activity.class);
                    startActivity(intent);
                    //关闭当前的页面
                    getActivity().finish();
                }

            }
        }
    };

    public TwoFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_two, container, false);


        fgText = (TextView) inflate.findViewById(R.id.fg_text);
        btn = (Button) inflate.findViewById(R.id.btn);


        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.cancel();

                //跳转
                Intent intent = new Intent(getActivity(), Main2Activity.class);
                startActivity(intent);
                getActivity().finish();
            }
        });

        return inflate;
    }
}
